/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.easy.core.utils;

import java.util.TimeZone;

import com.easy.core.jackson.NullValueSerializerProvider;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

/**
 * 序列号工具类
 *
 * @author Jasmine
 * @since 1.0.0
 */
public class JsonUtils {

    public static final Object object = new Object();

    public static ObjectMapper objectMapper;

    static {
        try {
            objectMapper = ApplicationContextHolder.getBean(ObjectMapper.class);
        } catch (Exception ex) {
            objectMapper = configObjectMapper();
        }
    }

    public static String writeValueAsString(Object value) {
        String content = "";
        try {
            content = objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return content;
    }

    public static <T> T readValue(String content, Class<T> valueType) {
        T result;
        try {
            result = objectMapper.readValue(content, valueType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    public static ObjectMapper configObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        // 指定时区
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        objectMapper.setSerializerProvider(new NullValueSerializerProvider());
        // 忽略json字符串中不识别的属性
        // objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 忽略无法转换的对象 空对象不让序列化
        // objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // PrettyPrinter 格式化输出
        // objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        // NULL不参与序列化
        // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return objectMapper;
    }

    public static ObjectMapper getInstance() {
        return objectMapper;
    }
}
